﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Kinect;
using Microsoft.Samples.Kinect.SwipeGestureRecognizer;
using YourControl.ViewPicture.UserControls;
using Cursors = System.Windows.Input.Cursors;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;

namespace YourControl.ViewPicture
{
    public partial class MainWindow
    {
        //配置文件路径
        private string _filePath;

        private List<Resources.Model.Resources> _resources;
        private readonly Timer _mouseTimer;
        private KinectSensor _kinectSensor;
        public MainWindow()
        {
            InitializeComponent();
            Loaded += WindowLoaded;
            _mouseTimer = new Timer();
            _mouseTimer.Tick += MouseTimerElapsed;
            _mouseTimer.Interval = 1000;
            MouseMove += MainWindowMouseMove; 
            _mouseTimer.Start();
            MouseDoubleClick += MainWindowMouseDoubleClick;
        }

        

 

        void MainWindowMouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            PictureScrollViewer.ScrollToHorizontalOffset(PictureScrollViewer.HorizontalOffset + 320);
        }
 

        void MainWindowMouseMove(object sender, MouseEventArgs e)
        {
            _mouseTimer.Start();
            _mouseTime = 0;
        }

        private int _mouseTime;
        void MouseTimerElapsed(object sender, EventArgs e)
        {
            _mouseTime++;
            button1.Content = _mouseTime;
            if(_mouseTime > 5)
            {
                Cursor = Cursors.None;
                _mouseTimer.Stop();
                _mouseTime = 0;
            }
            else
            {
                Cursor = Cursors.Arrow;
            }

            var imageSource = new BitmapImage(new Uri("Content/" + 1 + ".jpg", UriKind.RelativeOrAbsolute));
            Background = new ImageBrush(imageSource);
        }

        void WindowLoaded(object sender, RoutedEventArgs e)
        {
            _filePath = AppDomain.CurrentDomain.BaseDirectory + @"Resources\Config.xml";
            var resourcesService = new Resources.Model.Resources(_filePath);
            _resources = resourcesService.Find();
           // this.GoFullscreen();
            foreach(var resource in _resources)
            {
                var albumControl = new AlbumControl(resource.Items);
                albumControl.Margin = new Thickness(5,0,5,0);
                Layout.Children.Add(albumControl);
            }

            //INIT KINECT
            _kinectSensor = KinectSensor.KinectSensors.FirstOrDefault();
            if(_kinectSensor != null)
            {
                _kinectSensor.SkeletonStream.EnableTrackingInNearRange = true;
                _kinectSensor.SkeletonStream.Enable();
                _kinectSensor.SkeletonFrameReady += KinectSensorSkeletonFrameReady;
                _activeRecognizer = CreateRecognizer();
                Title = _kinectSensor.Status.ToString();
                _kinectSensor.Start();
            }
        }

        /// <summary>
        /// Create a wired-up recognizer for running the slideshow.
        /// </summary>
        /// <returns>The wired-up recognizer.</returns>
        private Recognizer CreateRecognizer()
        {
            var recognizer = new Recognizer();
            recognizer.SwipeLeftDetected += (s, e) =>
                                                {
                                                    SendKeys.Send("{Left}");
                                                    //if(e.Skeleton.TrackingId.Equals(_nearestId))
                                                    //PictureScrollViewer.ScrollToHorizontalOffset(PictureScrollViewer.HorizontalOffset + PictureScrollViewer.ViewportWidth);
                                                };
            recognizer.SwipeRightDetected += (s, e) =>
                                                 {
                                                     SendKeys.Send("{Right}");
                                                     //if (e.Skeleton.TrackingId.Equals(_nearestId))
                                                         //PictureScrollViewer.ScrollToHorizontalOffset(PictureScrollViewer.HorizontalOffset - PictureScrollViewer.ViewportWidth);
                                                 };
            return recognizer;
        }

        /// <summary>
        /// Array to receive skeletons from sensor, resize when needed.
        /// </summary>
        private Skeleton[] _skeletons = new Skeleton[0];
        /// <summary>
        /// The ID if the skeleton to be tracked.
        /// </summary>
        private int _nearestId = -1;

        /// <summary>
        /// The recognizer being used.
        /// </summary>
        private Recognizer _activeRecognizer;

        void KinectSensorSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {
            using(var frame = e.OpenSkeletonFrame())
            {
                if(null == frame) return;
                if(frame.SkeletonArrayLength != _skeletons.Length)
                {
                    _skeletons = new Skeleton[frame.SkeletonArrayLength];
                }
                //get the skeletons.
                frame.CopySkeletonDataTo(_skeletons);
                var newNearestId = -1;
                var nearestDistance2 = double.MaxValue;
                foreach(var skeleton in _skeletons)
                {
                    if(skeleton.TrackingState != SkeletonTrackingState.Tracked) continue;
                    var distance2 = (skeleton.Position.X*skeleton.Position.X) +
                                    (skeleton.Position.Y*skeleton.Position.Y) +
                                    (skeleton.Position.Z*skeleton.Position.Z);
                    if(distance2 < nearestDistance2)
                    {
                        newNearestId = skeleton.TrackingId;
                        nearestDistance2 = distance2;
                    }
                }
                if(newNearestId != _nearestId)
                {
                    _nearestId = newNearestId;
                }
                _activeRecognizer.Recognize(sender,frame,_skeletons);
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.Close(); 
        }
    }
}
